//
//  EDExchangeLevelViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/15.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDExchangeLevelViewController.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "ExchangeLevelCollectionViewCell.h"
#import "EDExchangeModel.h"
#import "NoNetworkView.h"
#import "ExchangeHeaderView.h"
@interface EDExchangeLevelViewController ()
<UICollectionViewDataSource, CHTCollectionViewDelegateWaterfallLayout>
{
    NSInteger _pageNum;
}
@property (nonatomic, strong)  UICollectionView *collectionView;
@property (nonatomic,strong) NoNetworkView * workView;
@property (nonatomic,strong) ExchangeHeaderView * topHeaderView;
@end
@implementation EDExchangeLevelViewController
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.topHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 50);
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNum = 0;
    [self setupUI];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refushData)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    [header beginRefreshing];
    self.collectionView.mj_header = header;
    
    
    
    
    
}

-(void)setupUI{
 
    self.topHeaderView = [[NSBundle mainBundle]loadNibNamed:@"ExchangeHeaderView" owner:self options:nil].lastObject;
    self.topHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 50);
    
    [self.view addSubview:self.topHeaderView];
    
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
    layout.headerHeight = 0;
    layout.footerHeight = 0;
    layout.minimumColumnSpacing = 25;
    layout.minimumInteritemSpacing = 20;
    layout.columnCount = 2;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, self.topHeaderView.bottom, kScreenWidth-40, kScreenHeight-kStatusBarAndNavigationBarHeight-100) collectionViewLayout:layout];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ExchangeLevelCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ExchangeLevelCollectionViewCell"];
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
      _collectionView.backgroundColor =kRGBColor(245, 245, 245);
    [self .view addSubview:self.collectionView];
    
}
-(void)refushData{
    //UserCenter_getChipInfo
    [self refushMyInfoData];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCenter_getChipInfo"];
    NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
    [diccc setValue:@(0) forKey:@"curpage"];
    
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        STRONGSELFFor(weakSelf);
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
//        NSDictionary  *dict = [dict001 jsonDict:@"data"];
        if ([[dict001 jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            [strongSelf.modelsArry removeAllObjects];
            NSArray *  dataArr = [dict001 jsonArray:@"data"];
            for (NSDictionary * modelDicc in dataArr) {
                EDExchangeModel * modell = [[EDExchangeModel alloc]initWithDictionary:modelDicc error:nil];
                [strongSelf.modelsArry addObject:modell];
            }
            
            
        }else{
            [JMNotifyView showNotify:[dict001 jsonString:@"message"]  isSuccessful:NO];
        }

        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self placeholderViewWithFrame:self.collectionView.frame NoNetwork:NO];
        });
        [self.collectionView.mj_header endRefreshing];
        [strongSelf.collectionView reloadData];
        NSLog(@"User_welfareMobileActionWelfareCore---%@",dict001);
        
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"error----%@",error);
        STRONGSELFFor(weakSelf);
        [strongSelf.collectionView.mj_header endRefreshing];
        //  [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
    
}

-(void)refushMyInfoData{
    //myUserNavigationDatd
  //  [self showLoadingAnimation];
    if (!kDictIsEmpty([DJLoginHelper sharedInstance].cj_UserDicc)) {
        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[DJLoginHelper sharedInstance].cj_UserDicc];
        self.topHeaderView.vipText.text =[NSString stringWithFormat:@"%@",[dict jsonString:@"vip"]];
        self.topHeaderView.fabiNum.text =[NSString stringWithFormat:@"%@",[dict  jsonString:@"coin"]];
    }
    [self.ks_TableView reloadData];
    
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_getUserInfos"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        STRONGSELFFor(weakSelf);
        [self stopLoadingAnimation];
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            [[DJLoginHelper sharedInstance]save_UserInfo:[dict jsonDict:@"data"]];
            strongSelf.topHeaderView.fabiNum.text =[NSString stringWithFormat:@"%@",[[dict jsonDict:@"data"]  jsonString:@"coin"]];
            strongSelf.topHeaderView.vipText.text =[NSString stringWithFormat:@"%@",[[dict jsonDict:@"data"]  jsonString:@"vip"]];
           
        }else{
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"error----%@",error);
        [self stopLoadingAnimation];
    }];
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.modelsArry.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ExchangeLevelCollectionViewCell *cell = (ExchangeLevelCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"ExchangeLevelCollectionViewCell" forIndexPath:indexPath];
    cell.modell = self.modelsArry[indexPath.item];
    WEAKSELF
    [cell.duihuanBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf duihuanClick:indexPath];
    }];
    return cell;
}
-(void)duihuanClick:(NSIndexPath*)indexptah{
    EDExchangeModel * model = self.modelsArry[indexptah.row];
  //  Center_exchangeChip
   [self showLoadingAnimation];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Center_exchangeChip"];
    NSMutableDictionary * jsonDicc = [NSMutableDictionary dictionary];
    [jsonDicc setValue:model.id forKey:@"id"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:jsonDicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            YYLog(@"loadDailySignPromotion----%@",dict001);
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"success" andTitleStr:[dict001 jsonString:@"data"] andlightStr:@""];
                [toast showLXAlertView];
                [self refushMyInfoData];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    

}

#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((kScreenWidth-55)/2, 305);
    
    
}

- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.modelsArry.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        _workView.centerX = self.collectionView.centerX-20;
        [self.collectionView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
}

@end
